﻿using CrawlerFramework.Translator;
using System;
using System.Data.Entity;

namespace CrawlerFramework.DataConverter
{
    public abstract class BaseDataConverter : IDataConverter
    {
        private bool _disposed;

        private ITranslateService _translateService;

        public BaseDataConverter(DbContext sourceDbContext, DbContext targetDbContext)
        {
            this.SourceContext = sourceDbContext;
            this.TargetContext = targetDbContext;
        }

        public virtual System.Data.Entity.DbContext SourceContext
        {
            get;
            private set;
        }

        public virtual System.Data.Entity.DbContext TargetContext
        {
            get;
            private set;
        }

        public virtual Translator.ITranslateService TranslateService
        {
            get
            {
                if (_translateService == null)
                    _translateService = new GoogleTranslateService();
                return _translateService;
            }
            set
            {
                _translateService = value;
            }
        }

        public virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (SourceContext != null) SourceContext.Dispose();
                    if (TargetContext != null) TargetContext.Dispose();
                }

                _disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public abstract void Migrate();

        public virtual void MigrateManyRecords(System.Collections.Generic.IEnumerable<int> ids)
        {
            if (ids == null)
                return;
            foreach (var id in ids)
            {
                MigrateOneRecord(id);
            }
        }

        public abstract void MigrateOneRecord(int id);

        protected virtual string Translate(string text)
        {
            if (this.TranslateService == null || string.IsNullOrEmpty(text))
                return text;
            return this.TranslateService.Translate(text);
        }


        public abstract void RemoveOneRecord(int id);

        public void RemoveManyRecords(System.Collections.Generic.IEnumerable<int> ids)
        {
            if (ids != null)
            {
                foreach (var id in ids)
                {
                    RemoveOneRecord(id);
                }
            }
        }
    }
}